package com.dongnam.quanly.web.nghiepvu.kho.nhapxuatkho;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.ChiTietPhieuNhapXuatController;
import com.dongnam.quanly.common.controller.DonHangController;
import com.dongnam.quanly.common.controller.PhieuNhapXuatController;
import com.dongnam.quanly.common.controller.TonKhoController;
import com.dongnam.quanly.common.controller.VatTuHangHoaController;
import com.dongnam.quanly.common.model.ChiTietPhieuNhapXuat;
import com.dongnam.quanly.common.model.DonHang;
import com.dongnam.quanly.common.model.PhieuNhapXuat;
import com.dongnam.quanly.common.model.TonKho;
import com.dongnam.quanly.common.model.VatTuHangHoa;
import com.dongnam.quanly.common.model.enumtype.LoaiDonHang;
import com.dongnam.quanly.common.model.enumtype.LoaiPhieu;
import com.dongnam.quanly.common.model.enumtype.TinhChatVTHH;
import com.dongnam.quanly.common.model.enumtype.TrangThaiDonHang;
import com.dongnam.quanly.common.model.enumtype.TrangThaiTonKho;
import com.dongnam.quanly.common.util.CreateIDUtil;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.util.DateFormatUtil;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "PhieuNhapXuatBean")
@SessionScoped
public class PhieuNhapXuatBean implements Serializable {

	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(PhieuNhapXuatBean.class);

	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;

	// for add and edit a PhieuNhapXuat
	private PhieuNhapXuat phieuNhapXuat;
	private boolean edit = false;

	private StreamedContent file;

	// for access database
	private PhieuNhapXuatController phieuNhapXuatController;
	private ChiTietPhieuNhapXuatController chiTietNhapXuatController;
	private TonKhoController tonkhoController;
	private VatTuHangHoaController vthhController;
	private DonHangController donhangController;

	// show data on table
	private List<PhieuNhapXuat> listPhieuNhapXuat;
	private List<PhieuNhapXuat> filteredPhieuNhapXuat;

	private PhieuNhapXuat selectedPhieuNhapXuat;

	// for show chi tiet don hang on table
	private List<ChiTietPhieuNhapXuat> listChiTietNhapXuat;
	private ChiTietPhieuNhapXuat selectedChiTietPhieuNhapXuat;
	private List<ChiTietPhieuNhapXuat> listChiTietNhapXuatOriginal;

	// for add chi tiet phieu nhap
	private String maVthh;
	private String masanpham;
	private double dongia;
	private String serialNumber;
	private String productName;
	private String soPhieuNhapXuat;
	private List<VatTuHangHoa> listVatTuHangHoa;
	private List<DonHang> listDH;
	private boolean nhapHang = false;
	private boolean xuatHang = false;
	private String tinhchatVTHH = "";
	private int soLuongForXuatKho;
	private int soLuongForNhapKho;
	private int tongTonKho;

	private List<TonKho> selectedTonKhos;
	private List<TonKho> listTonKho;

	public int getTongTonKho() {
		return tongTonKho;
	}

	public void setTongTonKho(int tongTonKho) {
		this.tongTonKho = tongTonKho;
	}

	public int getSoLuongForXuatKho() {
		return soLuongForXuatKho;
	}

	public void setSoLuongForXuatKho(int soLuongForXuatKho) {
		this.soLuongForXuatKho = soLuongForXuatKho;
	}

	public int getSoLuongForNhapKho() {
		return soLuongForNhapKho;
	}

	public void setSoLuongForNhapKho(int soLuongForNhapKho) {
		this.soLuongForNhapKho = soLuongForNhapKho;
	}

	public String getMasanpham() {
		return masanpham;
	}

	public void setMasanpham(String masanpham) {
		this.masanpham = masanpham;
	}

	public String getTinhchatVTHH() {
		return tinhchatVTHH;
	}

	public void setTinhchatVTHH(String tinhchatVTHH) {
		this.tinhchatVTHH = tinhchatVTHH;
	}

	public List<PhieuNhapXuat> getFilteredPhieuNhapXuat() {
		return filteredPhieuNhapXuat;
	}

	public void setFilteredPhieuNhapXuat(List<PhieuNhapXuat> filteredPhieuNhapXuat) {
		this.filteredPhieuNhapXuat = filteredPhieuNhapXuat;
	}

	public List<TonKho> getSelectedTonKhos() {
		return selectedTonKhos;
	}

	public void setSelectedTonKhos(List<TonKho> selectedTonKhos) {
		this.selectedTonKhos = selectedTonKhos;
	}

	public List<TonKho> getListTonKho() {
		return listTonKho;
	}

	public void setListTonKho(List<TonKho> listTonKho) {
		this.listTonKho = listTonKho;
	}

	public boolean isXuatHang() {
		return xuatHang;
	}

	public void setXuatHang(boolean xuatHang) {
		this.xuatHang = xuatHang;
	}

	public boolean isNhapHang() {
		return nhapHang;
	}

	public void setNhapHang(boolean nhapHang) {
		this.nhapHang = nhapHang;
	}

	public void loadPhieuNhapXuat() {

		this.listPhieuNhapXuat = getPhieuNhapXuatController().findAll("orderNumber", "DESCENDING");
	}

	public ChiTietPhieuNhapXuat getSelectedChiTietPhieuNhapXuat() {
		return selectedChiTietPhieuNhapXuat;
	}

	public void setSelectedChiTietPhieuNhapXuat(ChiTietPhieuNhapXuat selectedChiTietPhieuNhapXuat) {
		this.selectedChiTietPhieuNhapXuat = selectedChiTietPhieuNhapXuat;
	}

	public List<DonHang> getListDH() {
		return listDH;
	}

	public void setListDH(List<DonHang> listDH) {
		this.listDH = listDH;
	}

	public List<ChiTietPhieuNhapXuat> getListChiTietNhapXuatOriginal() {
		return listChiTietNhapXuatOriginal;
	}

	public void setListChiTietNhapXuatOriginal(List<ChiTietPhieuNhapXuat> listChiTietNhapXuatOriginal) {
		this.listChiTietNhapXuatOriginal = listChiTietNhapXuatOriginal;
	}

	public PhieuNhapXuatBean() {
		super();
		phieuNhapXuat = new PhieuNhapXuat();
		listPhieuNhapXuat = new ArrayList<PhieuNhapXuat>();
		loadPhieuNhapXuat();

		listDH = new ArrayList<DonHang>();
	}

	public String checkDate(Date value) {
		if (null == value) {
			return " ";
		} else {
			return value.toString();
		}
	}

	public void downloadFileCSV() {
		// Todo
		File excelfile = new File("Phieu_Nhap_Xuat.xls");
		List<PhieuNhapXuat> list = getPhieuNhapXuatController().findAll("orderNumber", "DESCENDING");
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 30);
			sheet.setColumnView(5, 30);
			sheet.setColumnView(6, 30);
			sheet.setColumnView(7, 30);
			sheet.setColumnView(8, 30);

			sheet.addCell(new Label(0, 0, "Số Chứng Từ", titleformat));
			sheet.addCell(new Label(1, 0, "Ngày Lập ", titleformat));
			sheet.addCell(new Label(2, 0, "Loại Phiếu", titleformat));
			sheet.addCell(new Label(3, 0, "Kho Hàng", titleformat));
			sheet.addCell(new Label(4, 0, "Nhân Viên ", titleformat));
			sheet.addCell(new Label(5, 0, "Đơn Hàng", titleformat));
			sheet.addCell(new Label(6, 0, "Tài Khoản Nợ", titleformat));
			sheet.addCell(new Label(7, 0, "Tài Khoản Có", titleformat));
			sheet.addCell(new Label(8, 0, "Có Hóa Đơn", titleformat));

			for (int i = 0; i < length; i++) {

				sheet.addCell(new Label(0, i + 1, list.get(i).getSoChungTu(), contentformat));
				sheet.addCell(new Label(1, i + 1, checkDate(list.get(i).getNgayLap()), contentformat));
				sheet.addCell(new Label(2, i + 1, list.get(i).getLoaiPhieu().name(), contentformat));
				sheet.addCell(new Label(3, i + 1, list.get(i).getKhoHang(), contentformat));
				sheet.addCell(new Label(4, i + 1, list.get(i).getNguoiLap(), contentformat));
				sheet.addCell(new Label(5, i + 1, list.get(i).getDonHang(), contentformat));
				sheet.addCell(new Label(6, i + 1, list.get(i).getSoTaiKhoanCo(), contentformat));
				sheet.addCell(new Label(7, i + 1, list.get(i).getSoTaiKhoanNo(), contentformat));

				sheet.addCell(new Label(8, i + 1, String.valueOf(list.get(i).isCoHoaDon()), contentformat));

			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv", "Phieu_Nhap_Xuat.xls",
					"UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void handleFileUpload(FileUploadEvent event) {
		// ToDo
		logger.debug("process upload file : Phieu_Nhap_Xuat.xls ");
		Workbook w;
		boolean rollback = false;
		List<PhieuNhapXuat> list = new ArrayList<PhieuNhapXuat>();
		try {
			w = Workbook.getWorkbook(event.getFile().getInputstream());
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines

			for (int row = 1; row < sheet.getRows(); row++) {

				logger.debug("row " + row);

				Cell cell_sCT = sheet.getCell(0, row);
				Cell cell_ngayLap = sheet.getCell(1, row);
				Cell cell_loaiPhieu = sheet.getCell(2, row);
				Cell cell_khoHang = sheet.getCell(3, row);
				Cell cell_nguoiLap = sheet.getCell(4, row);
				Cell cell_donHang = sheet.getCell(5, row);
				Cell cell_sTKN = sheet.getCell(6, row);
				Cell cell_sTKC = sheet.getCell(7, row);
				Cell cell_cHD = sheet.getCell(8, row);

				PhieuNhapXuat pnx = new PhieuNhapXuat();
				pnx.setSoChungTu(cell_sCT.getContents());

				pnx.setNgayLap(DateFormatUtil.String2Date("dd-MM-yyyy", cell_ngayLap.getContents()));
				pnx.setLoaiPhieu(LoaiPhieu.valueOf(cell_loaiPhieu.getContents()));
				pnx.setKhoHang(cell_khoHang.getContents());
				pnx.setNguoiLap(cell_nguoiLap.getContents());
				pnx.setDonHang(cell_donHang.getContents());
				pnx.setSoTaiKhoanNo(cell_sTKN.getContents());
				pnx.setSoTaiKhoanNo(cell_sTKC.getContents());
				pnx.setCoHoaDon(Boolean.getBoolean(cell_cHD.getContents()));
				list.add(pnx);
			}
		} catch (BiffException | IOException e) {
			e.printStackTrace();
			rollback = true;
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		if (!rollback) {
			getPhieuNhapXuatController().batchSaveOrUpdate(list);
		}

		loadPhieuNhapXuat();
	}

	public void resetFormAdd() {
		this.phieuNhapXuat = new PhieuNhapXuat();

	}

	public void loadListDonHang(LoaiPhieu loaiPhieu) {
		LoaiDonHang loaidonhang = null;
		if (loaiPhieu.equals(LoaiPhieu.PHIEU_NHAP)) {
			loaidonhang = LoaiDonHang.MUA_HANG;
		} else if (loaiPhieu.equals(LoaiPhieu.PHIEU_XUAT)) {
			loaidonhang = LoaiDonHang.BAN_HANG;
		}

		if (loaidonhang != null)
			listDH = getDonhangController().getListDonHang(new TrangThaiDonHang[]{TrangThaiDonHang.DANG_THUC_HIEN,TrangThaiDonHang.HOAN_TAT_HOADON}, loaidonhang);
		else
			listDH = getDonhangController().getListDonHang(TrangThaiDonHang.DANG_THUC_HIEN);
		if (listDH == null)
			listDH = new ArrayList<DonHang>();
	}

	public void notifyAdd() {
		edit = false;
		resetFormAdd();
		// this.phieuNhapXuat.setSoChungTu(CreateIDUtil.createDonHangID());

		if (listChiTietNhapXuat == null)
			listChiTietNhapXuat = new ArrayList<ChiTietPhieuNhapXuat>();
		listChiTietNhapXuat.clear();

	}

	public void notifyEdit(PhieuNhapXuat phieuNhapXuat) {
		edit = true;
		this.phieuNhapXuat = new PhieuNhapXuat(phieuNhapXuat);
		this.soPhieuNhapXuat = this.phieuNhapXuat.getSoChungTu();
		if (listChiTietNhapXuat == null)
			listChiTietNhapXuat = new ArrayList<ChiTietPhieuNhapXuat>();
		listChiTietNhapXuat.clear();

		this.listChiTietNhapXuat = getChiTietNhapXuatController().getListChiTietPNXBySoPhieu(
				this.phieuNhapXuat.getSoChungTu());
		if (this.listChiTietNhapXuat != null) {
			if (listChiTietNhapXuatOriginal == null)
				listChiTietNhapXuatOriginal = new ArrayList<ChiTietPhieuNhapXuat>();
			listChiTietNhapXuatOriginal.clear();

			int length = this.listChiTietNhapXuat.size();
			for (int i = 0; i < length; i++) {
				ChiTietPhieuNhapXuat ctpnx = new ChiTietPhieuNhapXuat(this.listChiTietNhapXuat.get(i));

				this.listChiTietNhapXuatOriginal.add(ctpnx);
			}
		}

		updatelistMaVthhByDonHang(this.phieuNhapXuat.getDonHang());
	}

	public void resetProductOrderDetail() {

		this.maVthh = "";
		this.serialNumber = "";
		this.productName = "";
		this.soLuongForNhapKho = 0;
		this.soLuongForXuatKho = 0;
		this.listTonKho = new ArrayList<TonKho>();
		this.selectedTonKhos = new ArrayList<TonKho>();

	}

	public void notifyAddChiTietPhieuNhapXuat() {

		RequestContext context = RequestContext.getCurrentInstance();
		if (this.phieuNhapXuat.getDonHang() == null || this.phieuNhapXuat.getDonHang().length() == 0) {
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Yêu cầu chọn đơn hàng", "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
			context.addCallbackParam("opSuccess", false);
		} else {

			resetProductOrderDetail();
			context.addCallbackParam("opSuccess", true);
		}
	}

	public List<VatTuHangHoa> getListMaVthhByDonHang() {
		return null;

	}

	public void addChiTietPhieuNhapXuat() {
		if (this.xuatHang) {

			if (this.tinhchatVTHH.equals(TinhChatVTHH.VTHH_KHONG_SERIAL.name())) {

				RequestContext context = RequestContext.getCurrentInstance();
				TonKho tk = getTonkhoController().getById(this.maVthh, true);

				ChiTietPhieuNhapXuat ctphieu = new ChiTietPhieuNhapXuat();
				ctphieu.setMaVthh(this.maVthh);
				ctphieu.setTenVTHH(getVthhController().getById(this.maVthh, true).getTenVTHH());
				ctphieu.setPhieuNhapXuat(this.soPhieuNhapXuat);
				ctphieu.setProductName(tk.getProductName());
				ctphieu.setSerialNumber(tk.getSerialNumber());
				ctphieu.setSoLuong(this.soLuongForXuatKho);
				ctphieu.setTinhChatVTHH(TinhChatVTHH.VTHH_KHONG_SERIAL.name());
				tk.setLock(true);
				this.listChiTietNhapXuat.add(ctphieu);
				context.addCallbackParam("opSuccess", true);
			} else if (this.tinhchatVTHH.equals(TinhChatVTHH.VTHH_CO_SERIAL.name())) {

				RequestContext context = RequestContext.getCurrentInstance();
				for (int i = 0; i < this.selectedTonKhos.size(); i++) {
					ChiTietPhieuNhapXuat ctphieu = new ChiTietPhieuNhapXuat();
					ctphieu.setMaVthh(this.maVthh);
					ctphieu.setTenVTHH(getVthhController().getById(this.maVthh, true).getTenVTHH());
					ctphieu.setPhieuNhapXuat(this.soPhieuNhapXuat);
					ctphieu.setProductName(this.selectedTonKhos.get(i).getProductName());
					ctphieu.setSerialNumber(this.selectedTonKhos.get(i).getSerialNumber());
					ctphieu.setSoLuong(1);
					ctphieu.setTinhChatVTHH(TinhChatVTHH.VTHH_CO_SERIAL.name());
					this.selectedTonKhos.get(i).setLock(true);
					this.listChiTietNhapXuat.add(ctphieu);

				}

				getTonkhoController().batchSaveOrUpdate(this.selectedTonKhos);

				context.addCallbackParam("opSuccess", true);
			}

		} else if (this.nhapHang) {

			VatTuHangHoa vthh = getVthhController().getById(this.maVthh, true);
			if (this.tinhchatVTHH.equals(TinhChatVTHH.VTHH_CO_SERIAL.name())) {
				RequestContext context = RequestContext.getCurrentInstance();
				ChiTietPhieuNhapXuat ctphieu = new ChiTietPhieuNhapXuat();
				ctphieu.setMaVthh(this.maVthh);
				ctphieu.setTenVTHH(vthh.getTenVTHH());
				ctphieu.setPhieuNhapXuat(this.soPhieuNhapXuat);
				ctphieu.setProductName(this.productName);
				ctphieu.setSerialNumber(this.serialNumber);
				ctphieu.setSoLuong(1);
				ctphieu.setTinhChatVTHH(TinhChatVTHH.VTHH_CO_SERIAL.name());
				this.listChiTietNhapXuat.add(ctphieu);

				context.addCallbackParam("opSuccess", true);

			} else if (this.tinhchatVTHH.equals(TinhChatVTHH.VTHH_KHONG_SERIAL.name())) {
				RequestContext context = RequestContext.getCurrentInstance();
				ChiTietPhieuNhapXuat ctphieu = new ChiTietPhieuNhapXuat();
				ctphieu.setMaVthh(this.maVthh);
				ctphieu.setTenVTHH(vthh.getTenVTHH());
				ctphieu.setPhieuNhapXuat(this.soPhieuNhapXuat);
				ctphieu.setProductName(vthh.getTenVTHH());
				ctphieu.setSerialNumber(this.maVthh);
				ctphieu.setSoLuong(this.soLuongForNhapKho);
				ctphieu.setTinhChatVTHH(TinhChatVTHH.VTHH_KHONG_SERIAL.name());
				this.listChiTietNhapXuat.add(ctphieu);

				context.addCallbackParam("opSuccess", true);
			}

		}

	}

	public void save() {
		RequestContext context = RequestContext.getCurrentInstance();
		try {

			this.phieuNhapXuat.setOrderNumber(Long.parseLong(this.phieuNhapXuat.getSoChungTu().substring(3)));
			getPhieuNhapXuatController().makePersistent(this.phieuNhapXuat);
			loadPhieuNhapXuat();

			if (edit) {
				getChiTietNhapXuatController().batchDelete(this.listChiTietNhapXuatOriginal);

				getChiTietNhapXuatController().batchPersist(this.listChiTietNhapXuat);
			} else {
				getChiTietNhapXuatController().batchPersist(this.listChiTietNhapXuat);

				// xu ly cho truong hop nhap hang
				if (this.phieuNhapXuat.getLoaiPhieu().equals(LoaiPhieu.PHIEU_NHAP)) {
					List<TonKho> listTonKho = new ArrayList<TonKho>();
					int length = this.listChiTietNhapXuat.size();
					for (int i = 0; i < length; i++) {
						TonKho tk = new TonKho();
						tk.setKhoHang(this.phieuNhapXuat.getKhoHang());
						tk.setVatTuHangHoa(this.listChiTietNhapXuat.get(i).getMaVthh());
						tk.setSerialNumber(this.listChiTietNhapXuat.get(i).getSerialNumber());
						tk.setProductName(this.listChiTietNhapXuat.get(i).getProductName());
						tk.setSoLuong(this.listChiTietNhapXuat.get(i).getSoLuong());
						tk.setPhieuNhapKho(this.phieuNhapXuat.getSoChungTu());
						tk.setTrangThai(TrangThaiTonKho.TRONGKHO);
						tk.setLock(false);
						tk.setOrderNumber(this.phieuNhapXuat.getOrderNumber());

						if (this.listChiTietNhapXuat.get(i).getTinhChatVTHH()
								.equals(TinhChatVTHH.VTHH_CO_SERIAL.name())) {
							listTonKho.add(tk);
						} else if (this.listChiTietNhapXuat.get(i).getTinhChatVTHH()
								.equals(TinhChatVTHH.VTHH_KHONG_SERIAL.name())) {
							TonKho temp = getTonkhoController().getById(tk.getSerialNumber(), true);

							if (temp != null) {
								tk.setSoLuong(temp.getSoLuong() + tk.getSoLuong());
							}

							getTonkhoController().makePersistent(tk);
						}

					}

					getTonkhoController().batchPersist(listTonKho);
				}
				// xu ly cho truong hop xuat hang
				else {
					List<TonKho> listTonKho = new ArrayList<TonKho>();

					int length = this.listChiTietNhapXuat.size();

					for (int i = 0; i < length; i++) {
						TonKho tk = getTonkhoController().getById(this.listChiTietNhapXuat.get(i).getSerialNumber(),
								true);

						tk.setPhieuXuatKho(this.phieuNhapXuat.getSoChungTu());

						if (this.listChiTietNhapXuat.get(i).getTinhChatVTHH()
								.equals(TinhChatVTHH.VTHH_CO_SERIAL.name())) {
							listTonKho.add(tk);

							tk.setTrangThai(TrangThaiTonKho.XUATKHO);
						} else if (this.listChiTietNhapXuat.get(i).getTinhChatVTHH()
								.equals(TinhChatVTHH.VTHH_KHONG_SERIAL.name())) {

							tk.setSoLuong(tk.getSoLuong() - this.listChiTietNhapXuat.get(i).getSoLuong());

							getTonkhoController().makePersistent(tk);
						}

						listTonKho.add(tk);
					}

					getTonkhoController().batchSaveOrUpdate(listTonKho);

				}
			}

			context.addCallbackParam("opSuccess", true);
		} catch (Exception e) {
			e.printStackTrace();
			context.addCallbackParam("opSuccess", false);
		}

	}

	public DonHangController getDonhangController() {

		if (donhangController == null)
			donhangController = new DonHangController();

		return donhangController;
	}

	public void setDonhangController(DonHangController donhangController) {
		this.donhangController = donhangController;
	}

	public List<VatTuHangHoa> getListVatTuHangHoa() {
		return listVatTuHangHoa;
	}

	public void setListVatTuHangHoa(List<VatTuHangHoa> listVatTuHangHoa) {
		this.listVatTuHangHoa = listVatTuHangHoa;
	}

	public VatTuHangHoaController getVthhController() {
		if (vthhController == null)
			vthhController = new VatTuHangHoaController();
		return vthhController;
	}

	public void setVthhController(VatTuHangHoaController vthhController) {
		this.vthhController = vthhController;
	}

	public TonKhoController getTonkhoController() {

		if (tonkhoController == null)
			tonkhoController = new TonKhoController();

		return tonkhoController;
	}

	public void setTonkhoController(TonKhoController tonkhoController) {
		this.tonkhoController = tonkhoController;
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public PhieuNhapXuat getPhieuNhapXuat() {
		return phieuNhapXuat;
	}

	public void setPhieuNhapXuat(PhieuNhapXuat phieuNhapXuat) {
		this.phieuNhapXuat = phieuNhapXuat;
	}

	public boolean isEdit() {
		return edit;
	}

	public void setEdit(boolean edit) {
		this.edit = edit;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public PhieuNhapXuatController getPhieuNhapXuatController() {

		if (phieuNhapXuatController == null) {
			phieuNhapXuatController = new PhieuNhapXuatController();
		}

		return phieuNhapXuatController;
	}

	public void setPhieuNhapXuatController(PhieuNhapXuatController phieuNhapXuatController) {
		this.phieuNhapXuatController = phieuNhapXuatController;
	}

	public ChiTietPhieuNhapXuatController getChiTietNhapXuatController() {

		if (chiTietNhapXuatController == null) {
			chiTietNhapXuatController = new ChiTietPhieuNhapXuatController();
		}

		return chiTietNhapXuatController;
	}

	public void setChiTietNhapXuatController(ChiTietPhieuNhapXuatController chiTietNhapXuatController) {
		this.chiTietNhapXuatController = chiTietNhapXuatController;
	}

	public List<PhieuNhapXuat> getListPhieuNhapXuat() {

		return listPhieuNhapXuat;
	}

	public void setListPhieuNhapXuat(List<PhieuNhapXuat> listPhieuNhapXuat) {
		this.listPhieuNhapXuat = listPhieuNhapXuat;
	}

	public PhieuNhapXuat getSelectedPhieuNhapXuat() {
		return selectedPhieuNhapXuat;
	}

	public void setSelectedPhieuNhapXuat(PhieuNhapXuat selectedPhieuNhapXuat) {
		this.selectedPhieuNhapXuat = selectedPhieuNhapXuat;
	}

	public LoaiPhieu[] getListLoaiPhieu() {
		return LoaiPhieu.values();
	}

	public List<ChiTietPhieuNhapXuat> getListPODetail() {
		return listChiTietNhapXuat;
	}

	public void setListPODetail(List<ChiTietPhieuNhapXuat> listPODetail) {
		this.listChiTietNhapXuat = listPODetail;
	}

	public String getMaVthh() {
		return maVthh;
	}

	public void setMaVthh(String maVthh) {
		this.maVthh = maVthh;
	}

	public double getDongia() {
		return dongia;
	}

	public List<ChiTietPhieuNhapXuat> getListChiTietNhapXuat() {
		return listChiTietNhapXuat;
	}

	public void setListChiTietNhapXuat(List<ChiTietPhieuNhapXuat> listChiTietNhapXuat) {
		this.listChiTietNhapXuat = listChiTietNhapXuat;
	}

	public void setDongia(double dongia) {
		this.dongia = dongia;
	}

	public String getSerialNumber() {
		return serialNumber;
	}

	public void setSerialNumber(String serialNumber) {
		this.serialNumber = serialNumber;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public String getSoPhieuNhapXuat() {
		return soPhieuNhapXuat;
	}

	public void setSoPhieuNhapXuat(String soPhieuNhapXuat) {
		this.soPhieuNhapXuat = soPhieuNhapXuat;
	}

	public void reloadPage() {
		loadPhieuNhapXuat();
		resetFormAdd();
		resetProductOrderDetail();
		WebUtil.redirect("/pages/nghiepvu/kho/nhapXuatKho.xhtml");
	}

	private void updatelistMaVthhByDonHang(String donhang) {
		this.listVatTuHangHoa = getDonhangController().getListMaVthhByDonHang(donhang);
		if (this.listVatTuHangHoa == null)
			this.listVatTuHangHoa = new ArrayList<VatTuHangHoa>();

	}

	public void updateVatTuHangHoa(AjaxBehaviorEvent event) {
		String donhang = (String) ((UIOutput) event.getSource()).getValue();
		updatelistMaVthhByDonHang(donhang);

	}

	public void removePhieuNhapXuat() {

		if (this.selectedPhieuNhapXuat != null) {
			try {
				List<ChiTietPhieuNhapXuat> list = getChiTietNhapXuatController().getListChiTietPNXBySoPhieu(
						this.selectedPhieuNhapXuat.getSoChungTu());
				getChiTietNhapXuatController().batchDelete(list);
				getPhieuNhapXuatController().makeTransient(this.selectedPhieuNhapXuat);
				this.listPhieuNhapXuat.remove(this.selectedPhieuNhapXuat);

				if (this.selectedPhieuNhapXuat.getLoaiPhieu().equals(LoaiPhieu.PHIEU_NHAP)) {

					int length = list.size();
					for (int i = 0; i < length; i++) {
						if (list.get(i).getTinhChatVTHH().equals(TinhChatVTHH.VTHH_CO_SERIAL.name())) {
							TonKho tk1 = getTonkhoController().getById(list.get(i).getSerialNumber(), true);
							getTonkhoController().makeTransient(tk1);
						} else if (list.get(i).getTinhChatVTHH().equals(TinhChatVTHH.VTHH_KHONG_SERIAL.name())) {
							TonKho tk2 = getTonkhoController().getById(list.get(i).getSerialNumber(), true);
							tk2.setSoLuong(tk2.getSoLuong() - this.listChiTietNhapXuat.get(i).getSoLuong());
							getTonkhoController().makePersistent(tk2);
						}
					}

				} else {

					int length = list.size();
					for (int i = 0; i < length; i++) {
						if (this.listChiTietNhapXuat.get(i).getTinhChatVTHH()
								.equals(TinhChatVTHH.VTHH_CO_SERIAL.name())) {
							TonKho tk1 = getTonkhoController().getById(list.get(i).getSerialNumber(), true);

							tk1.setTrangThai(TrangThaiTonKho.TRONGKHO);
							tk1.setPhieuXuatKho("");

							getTonkhoController().makePersistent(tk1);
						} else if (this.listChiTietNhapXuat.get(i).getTinhChatVTHH()
								.equals(TinhChatVTHH.VTHH_KHONG_SERIAL.name())) {
							TonKho tk2 = getTonkhoController().getById(list.get(i).getSerialNumber(), true);
							tk2.setSoLuong(tk2.getSoLuong() + list.get(i).getSoLuong());
							getTonkhoController().makePersistent(tk2);
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	public void removeChiTietPhieuNhapXuat() {
		this.listChiTietNhapXuat.remove(this.selectedChiTietPhieuNhapXuat);

		TonKho tk = getTonkhoController().getById(this.selectedChiTietPhieuNhapXuat.getSerialNumber(), true);
		tk.setLock(false);

		getTonkhoController().makePersistent(tk);
	}

	public void changeLoaiPhieu(AjaxBehaviorEvent event) {
		LoaiPhieu loaiphieu = (LoaiPhieu) ((UIOutput) event.getSource()).getValue();

		if (loaiphieu.equals(LoaiPhieu.PHIEU_NHAP)) {
			nhapHang = true;
			xuatHang = false;
		} else {
			nhapHang = false;
			xuatHang = true;
		}
		this.soPhieuNhapXuat = CreateIDUtil.createPhieuNhapXuatID(loaiphieu);
		this.phieuNhapXuat.setSoChungTu(this.soPhieuNhapXuat);

		loadListDonHang(loaiphieu);
	}

	public void changeVatTuHangHoa(AjaxBehaviorEvent event) {
		String mavthh = (String) ((UIOutput) event.getSource()).getValue();

		VatTuHangHoa vthh = getVthhController().getById(mavthh, true);

		this.tinhchatVTHH = vthh.getTinhchat().name();

		if (this.xuatHang) {
			this.listTonKho = getTonkhoController().listTonKhoByMaVthh(mavthh);
			this.selectedTonKhos = new ArrayList<TonKho>();
		}
	}
}
